package netty.httpserver;

import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;

import java.nio.charset.Charset;

/**
 * HttpHandler {@link netty.httpserver} <br>
 *
 * @author zengjian
 * @date 2019/7/22 19:22
 * @since 1.0.0
 */
public class HttpHandler extends SimpleChannelInboundHandler<Object> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o) throws Exception {
        if (o instanceof HttpRequest) {
            HttpRequest request = (HttpRequest) o;
            System.out.println("接收到Http请求:\n" + request.toString());
            FullHttpResponse fullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
            buildFullHttpResponse(fullHttpResponse);
            channelHandlerContext.writeAndFlush(fullHttpResponse).addListener((ChannelFutureListener) future -> {
                if (future.isSuccess()) {
                    System.out.println("返回消息OK");
                } else {
                    System.out.println("返回消息失败");
                }
            });

        }
    }

    private void buildFullHttpResponse(FullHttpResponse response) {
        response.content().writeBytes("hello".getBytes(Charset.defaultCharset()));
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
    }
}